package com.lpf;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;

import java.io.IOException;

/**
 * 除了通过 GetRequest 请求根据 Document Id 进行查询之外，我们还可以通过 SearchRequest
 * 请求进行检索，在检索请求里面我们可以通过 QueryBuilder 构造具体的检索条件
 */
public class Main07 {

    public static void main(String[] args) throws IOException {

        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http"),
                        new HttpHost("localhost", 9200, "http")
                )
        );

        // 创建 SearchRequest 请求
        SearchRequest searchRequest = new SearchRequest("skywalking");

        // 通过 SearchSourceBuilder，用来构造检索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 通过id进行检索，这里查询 Id 为1和2的两个 Document
        searchSourceBuilder.query(QueryBuilders.idsQuery().addIds("1", "2"));

        searchRequest.source(searchSourceBuilder);

        // 发送 SearchRequest 请求
        SearchResponse searchResponse = client.search(searchRequest);

        // 遍历 SearchHit
        SearchHit[] searchHits = searchResponse.getHits().getHits();

        for (SearchHit searchHit : searchHits) {
            System.out.println(searchHit.getId() + ":" + searchHit.getSourceAsMap());
        }
    }
}